package org.qiancizhan.UI;

import java.util.Scanner;

import org.qiancizhan.Controller.UserController;
import org.qiancizhan.Model.DTO.LoginDTO;
import org.qiancizhan.Model.POJO.UserPOJO;
import org.qiancizhan.Utils.ThreadLocalUtil;

public class UserUI {
    private static final Scanner sc = new Scanner(System.in);
    private static final UserController userController = new UserController();

    public static void loginFn(){
        System.out.println("请输入用户名:");
        String username = sc.nextLine().trim();
        System.out.println("请输入密码:");
        String password = sc.nextLine().trim();
        UserPOJO loginData = userController.login(new LoginDTO(username, password));
        if (loginData == null) {
            System.out.println("用户名或密码错误,请重新登录");
            loginFn();
            return;
        }
        ThreadLocalUtil.set(loginData);
        System.out.println("登录成功!进入首页面");
        IndexUI.showIndexMenu();
    }
    public static void registerFn(){
        System.out.println("请输入用户名:");
        String username = sc.nextLine().trim();
        if(!username.matches("[A-Za-z0-9]{6,}")){
            System.out.println("用户名格式错误,请输入6位以上字母数字组合");
            registerFn();
            return;
        }
        System.out.println("请输入密码:");
        String password = sc.nextLine().trim();
        if(!password.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$")){
            System.out.println("密码格式错误,请输入8位以上大小写字母数字组合");
            registerFn();
            return;
        }
        System.out.println("确认密码:");
        String rePassword = sc.nextLine().trim();
        if (!password.equals(rePassword)) {
            System.out.println("密码不一致,重新输入");
            registerFn();
            return;
        }
        boolean result = userController.register(new LoginDTO(username,password));
        if(!result){
            System.out.println("用户名重复，请更换用户名");
            return;
        }
        System.out.println("注册成功");
        showLoginMenu();
    }

    public static void showLoginMenu() {
    System.out.println("1. 登录\t2. 注册\t0. 退出");
    while(true){
        String input = sc.nextLine().trim();
        switch (input) {
            case "1" -> {
                loginFn();
            }
            case "2" -> {
                registerFn();
            }
            case "0" -> {
                System.out.println("程序退出");
                System.exit(0);
            }
            default -> {
                System.out.println("请选择正确的选项");
            }
        }
    }
}
}
